Welcome to Hands on deep learning!

02.03.08 矩阵-向量积

在代码中使用张量表示矩阵-向量积,我们使用mv函数。 当我们为矩阵A和向量x调用torch.mv(A, x)时,会执行矩阵-向量积。 注意,A的列维数(沿轴1的长度)必须与x的维数(其长度)相同。

import torch

A = torch.arange(20, dtype=torch.float32).reshape(5, 4)

x = torch.arange(4).float() # 转为 float32

print(A)

print(x)

print(A.shape, x.shape)

print(torch.mv(A, x))

返回值:

tensor([[ 0., 1., 2., 3.],

[ 4., 5., 6., 7.],

[ 8., 9., 10., 11.],

[12., 13., 14., 15.],

[16., 17., 18., 19.]])

tensor([0., 1., 2., 3.])

torch.Size([5, 4]) torch.Size([4])

tensor([ 14., 38., 62., 86., 110.])